package org.budo.support.spring.web.argument.resolver.page;

import org.budo.support.dao.page.Page;
import org.budo.support.lang.util.StringUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public class BudoPageArgumentResolver implements HandlerMethodArgumentResolver {
    private Integer defaultPageSize;

    private String pageNumberKey = "pageNumber";

    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(Page.class);
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Page page = new Page();

        String pageNumber = webRequest.getParameter(this.getPageNumberKey());
        if (!StringUtil.isEmpty(pageNumber) && !"null".equalsIgnoreCase(pageNumber.trim())) {
            page.setPageNumber(Integer.valueOf(pageNumber));
        }

        String pageSize = webRequest.getParameter("pageSize");
        if (!StringUtil.isEmpty(pageSize) && !"null".equalsIgnoreCase(pageSize.trim())) {
            page.setPageSize(Integer.valueOf(pageSize));
        } else {
            page.setPageSize(this.getDefaultPageSize());
        }

        return page;
    }
}
